using UnityEngine;
using System.Collections;

/// MouseLook rotates the transform based on the mouse delta.
/// Minimum and Maximum values can be used to constrain the possible rotation

/// To make an FPS style character:
/// - Create a capsule.
/// - Add a rigid body to the capsule
/// - Add the MouseLook script to the capsule.
///   -> Set the mouse look to use LookX. (You want to only turn character but not tilt it)
/// - Add FPSWalker script to the capsule

/// - Create a camera. Make the camera a child of the capsule. Reset it's transform.
/// - Add a MouseLook script to the camera.
///   -> Set the mouse look to use LookY. (You want the camera to tilt up and down like a head. The character already turns.)
[AddComponentMenu("Camera-Control/Mouse Look")]
public class MouseLook : MonoBehaviour
{

    public float sensitivityX = 15F;
    public float sensitivityY = 15F;
    public float distance = 20;
    bool invertPitch = false; // Invert the X rotation axis. False: MouseDown=LookDown, True:MouseDown=LookUp
    // Whether to use transform.Rotate() or rigidbody.AddRelativeTorque();
    public Transform target;
    float oldx;
    void LateUpdate()
    {
        int invertPitchInt = (invertPitch) ? -1 : 1;

        // Actual mouse movement controls

        if (Input.GetAxis("Mouse X") != 0)
        {
            float x = Input.GetAxis("Mouse X") * sensitivityX;

            target.Rotate(Vector3.up * x);
        }
        if (Input.GetAxis("Mouse Y") != 0)
        {
            float y = invertPitchInt * Input.GetAxis("Mouse Y") * sensitivityY;
            target.Rotate(Vector3.left * y);
        }
        print(Input.GetAxis("Mouse X")+" "+ Input.GetAxis("Mouse Y"));
      smooth();
       transform.rotation = target.rotation; 
       setPosition();
    }
    private void smooth()
    {
       // print(target.localRotation.eulerAngles);
        if (target.localRotation.eulerAngles.x < 45 || target.localRotation.eulerAngles.x > 315)
        {
            if (target.localRotation.eulerAngles.z > 5.1 && target.localRotation.eulerAngles.z < 354.9)
            {
                if (target.localRotation.eulerAngles.z < 315)
                {
                    target.Rotate(Vector3.back * 5f);
                }
                else if (target.localRotation.eulerAngles.z > 45)
                {
                    target.Rotate(Vector3.forward * 5f);
                }
            }
        }
    }
    private void setPosition()
    {
        Vector3 wantedPosition = target.position + (target.rotation * Vector3.forward * distance);
        //transform.LookAt(target);
        transform.position = wantedPosition;
    }
    void Start()
    {
        // Make the rigid body not change rotation
        if (rigidbody)
            rigidbody.freezeRotation = true;
    }

}